<template>
  <el-drawer v-model="drawer" :direction="direction">
    <template #header>
      <h4>分配权限</h4>
    </template>
    <template #default>
      <!-- 
        ref : 设置tree的DOM节点,用户获取方法
        data : 绑定的数据
        show-checkbox : 展示box选择框
        default-expand-all : 默认全部展开
        node-key : 用于绑定的id,用于最后收集的getHalfCheckedKeys和getCheckedKeys
        default-expand-all : 全部展开
        props : 用于设置展示的文字和子级data名称
      -->
      <el-tree
        ref="tree"
        :data="allPermissionMenu"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="selectPermission"
        :props="defaultProps"
      />
    </template>
    <template #footer>
      <div>
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { reqAllRolePermission, reqSetRolePermission } from '@/api/acl/role'
import type { roleObj, ResponseRolePermission } from '@/api/acl/role/type'
import { ElMessage } from 'element-plus'
const drawer = ref(false)
const paramsData = reactive<roleObj>({
  roleName: '',
  id: 0,
})
const defaultProps = {
  children: 'children',
  label: 'name',
}
// 所有权限列表
const allPermissionMenu = ref<any>([])
const selectPermission = ref<any>([])
const getCurInfo = async (row: roleObj) => {
  Object.assign(paramsData, row)
  drawer.value = true
  const res: ResponseRolePermission = await reqAllRolePermission(
    paramsData.id as number,
  )
  if (res.code === 200) {
    allPermissionMenu.value = res.data
    selectPermission.value = filterSelect(allPermissionMenu.value, [])
  }
}
// 帅选已选择的id进行展示
const filterSelect = (allMenuList: any, initArr: any) => {
  allMenuList.forEach((item: any) => {
    if (item.select && item.level === 4) initArr.push(item.id)
    if (item.children && item.children.length)
      filterSelect(item.children, initArr)
  })
  return initArr
}
// 取消
const cancelClick = () => {
  drawer.value = false
}
const tree = ref()
// 确定
const confirmClick = async () => {
  const arr = tree.value.getCheckedKeys()
  const arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  const res = await reqSetRolePermission(paramsData.id as number, permissionId)
  if (res.code === 200) {
    cancelClick()
    ElMessage.success('分配成功')
    // 页面刷新
    window.location.reload()
  }
}

defineExpose({
  getCurInfo,
})
</script>
<script lang="ts">
export default {
  name: 'setRolePermission',
}
</script>
<style lang="scss" scoped></style>
